<template>
  <div class="job-container">
    <el-card class="job-header">
      <template #header>
        <div class="card-header">
          <div>
            <span class="header-title">定时任务管理</span>
            <span class="header-subtitle">管理系统中的所有定时任务，可以添加、修改、删除和执行任务</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd" v-hasPermi="['monitor:job:add']">
              <i class="el-icon-plus"></i> 新增
            </el-button>
            <el-button type="success" @click="handleExport" v-hasPermi="['monitor:job:export']">
              <i class="el-icon-download"></i> 导出
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input
            v-model="queryParams.jobName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-select v-model="queryParams.jobGroup" placeholder="请选择任务组名" clearable>
            <el-option
              v-for="dict in jobGroupOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            @click="handleBatchDelete"
            v-hasPermi="['monitor:job:remove']"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-video-play"
            @click="handleBatchExecute"
            v-hasPermi="['monitor:job:changeStatus']"
          >批量执行</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            @click="handleJobLog"
            v-hasPermi="['monitor:job:query']"
          >调度日志</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 任务表格 -->
      <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务编号" align="center" prop="jobId" />
        <el-table-column label="任务名称" align="center" prop="jobName" :show-overflow-tooltip="true" />
        <el-table-column label="任务组名" align="center" prop="jobGroup">
          <template #default="scope">
            <dict-tag :options="jobGroupOptions" :value="scope.row.jobGroup" />
          </template>
        </el-table-column>
        <el-table-column label="调用目标字符串" align="center" prop="invokeTarget" :show-overflow-tooltip="true" />
        <el-table-column label="cron执行表达式" align="center" prop="cronExpression" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
              v-hasPermi="['monitor:job:changeStatus']"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-hasPermi="['monitor:job:edit']">
              <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-hasPermi="['monitor:job:remove']">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="执行一次" placement="top" v-hasPermi="['monitor:job:changeStatus']">
              <el-button type="text" icon="el-icon-video-play" @click="handleRun(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="任务详情" placement="top" v-hasPermi="['monitor:job:query']">
              <el-button type="text" icon="el-icon-view" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="调度日志" placement="top" v-hasPermi="['monitor:job:query']">
              <el-button type="text" icon="el-icon-document" @click="handleJobLog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择">
                <el-option
                  v-for="dict in jobGroupOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="调用目标字符串" prop="invokeTarget">
              <el-input v-model="form.invokeTarget" placeholder="请输入调用目标字符串">
                <template #append>
                  <el-button type="primary" @click="handleShowInvokeTest">测试</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="Cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式">
                <template #append>
                  <el-button type="primary" @click="handleShowCronForm">生成表达式</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy">
                <el-radio
                  v-for="dict in misfirePolicyOptions"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent">
                <el-radio
                  v-for="dict in concurrentOptions"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Cron表达式生成器 -->
    <el-dialog title="Cron表达式生成器" v-model="cronVisible" width="800px" append-to-body>
      <cron-tab @hide="cronVisible = false" @fill="cronExpression => form.cronExpression = cronExpression"></cron-tab>
    </el-dialog>

    <!-- 任务详情 -->
    <el-dialog title="任务详情" v-model="detailVisible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务编号">{{ detailForm.jobId }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ detailForm.jobName }}</el-descriptions-item>
        <el-descriptions-item label="任务组名">
          <dict-tag :options="jobGroupOptions" :value="detailForm.jobGroup" />
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="cron表达式" :span="2">{{ detailForm.cronExpression }}</el-descriptions-item>
        <el-descriptions-item label="调用目标字符串" :span="2">{{ detailForm.invokeTarget }}</el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <dict-tag :options="statusOptions" :value="detailForm.status" />
        </el-descriptions-item>
        <el-descriptions-item label="是否并发">
          <dict-tag :options="concurrentOptions" :value="detailForm.concurrent" />
        </el-descriptions-item>
        <el-descriptions-item label="执行策略">
          <dict-tag :options="misfirePolicyOptions" :value="detailForm.misfirePolicy" />
        </el-descriptions-item>
        <el-descriptions-item label="下次执行时间">{{ nextExecuteTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import CronTab from '@/components/Cron/index.vue'
// import { parseTime } from '@/utils/common'

// 是否显示搜索表单
const showSearch = ref(true)

// 总条数
const total = ref(0)

// 定时任务表格数据
const jobList = ref([])

// 选中数组
const ids = ref([])
const names = ref([])

// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

// 显示弹出层
const open = ref(false)
// cron表达式弹出层
const cronVisible = ref(false)
// 详情弹出层
const detailVisible = ref(false)

// 弹出层标题
const title = ref('')

// 是否显示加载动画
const loading = ref(false)

// 下次执行时间
const nextExecuteTime = ref('')

// 表单参数
const form = reactive({
  jobId: undefined,
  jobName: undefined,
  jobGroup: undefined,
  invokeTarget: undefined,
  cronExpression: undefined,
  misfirePolicy: '1',
  concurrent: '1',
  status: '0',
  remark: undefined
})

// 详情表单
const detailForm = reactive({
  jobId: undefined,
  jobName: undefined,
  jobGroup: undefined,
  invokeTarget: undefined,
  cronExpression: undefined,
  misfirePolicy: undefined,
  concurrent: undefined,
  status: undefined,
  createTime: undefined,
  remark: undefined
})

// 表单校验
const rules = {
  jobName: [
    { required: true, message: '任务名称不能为空', trigger: 'blur' }
  ],
  jobGroup: [
    { required: true, message: '任务组名不能为空', trigger: 'change' }
  ],
  invokeTarget: [
    { required: true, message: '调用目标字符串不能为空', trigger: 'blur' }
  ],
  cronExpression: [
    { required: true, message: 'cron执行表达式不能为空', trigger: 'blur' }
  ]
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  jobName: undefined,
  jobGroup: undefined,
  status: undefined
})

// 字典数据
const jobGroupOptions = ref([
  { value: 'DEFAULT', label: '默认' },
  { value: 'SYSTEM', label: '系统' },
  { value: 'TASK', label: '任务' }
])

const statusOptions = ref([
  { value: '0', label: '正常' },
  { value: '1', label: '暂停' }
])

const misfirePolicyOptions = ref([
  { value: '1', label: '立即执行' },
  { value: '2', label: '执行一次' },
  { value: '3', label: '放弃执行' }
])

const concurrentOptions = ref([
  { value: '0', label: '允许' },
  { value: '1', label: '禁止' }
])

// 模拟数据
const mockJobs = [
  {
    jobId: 1,
    jobName: '系统默认（无参）',
    jobGroup: 'DEFAULT',
    invokeTarget: 'ryTask.ryNoParams',
    cronExpression: '0/10 * * * * ?',
    misfirePolicy: '1',
    concurrent: '1',
    status: '0',
    createTime: '2023-05-01 12:00:00',
    remark: '系统默认无参任务'
  },
  {
    jobId: 2,
    jobName: '系统默认（有参）',
    jobGroup: 'DEFAULT',
    invokeTarget: 'ryTask.ryParams(\'ry\')',
    cronExpression: '0/15 * * * * ?',
    misfirePolicy: '1',
    concurrent: '1',
    status: '1',
    createTime: '2023-05-01 12:00:00',
    remark: '系统默认有参任务'
  },
  {
    jobId: 3,
    jobName: '系统默认（多参）',
    jobGroup: 'DEFAULT',
    invokeTarget: 'ryTask.ryMultipleParams(\'ry\', true, 2000L, 316.50D, 100)',
    cronExpression: '0/20 * * * * ?',
    misfirePolicy: '2',
    concurrent: '0',
    status: '0',
    createTime: '2023-05-01 12:00:00',
    remark: '系统默认多参任务'
  },
  {
    jobId: 4,
    jobName: '清理临时文件',
    jobGroup: 'SYSTEM',
    invokeTarget: 'systemTask.cleanTempFiles()',
    cronExpression: '0 0 0 * * ?',
    misfirePolicy: '3',
    concurrent: '1',
    status: '0',
    createTime: '2023-05-02 10:00:00',
    remark: '每天凌晨执行一次，清理系统临时文件'
  },
  {
    jobId: 5,
    jobName: '数据库备份',
    jobGroup: 'SYSTEM',
    invokeTarget: 'systemTask.backupDatabase()',
    cronExpression: '0 0 2 * * ?',
    misfirePolicy: '1',
    concurrent: '1',
    status: '0',
    createTime: '2023-05-02 10:30:00',
    remark: '每天凌晨2点执行数据库备份'
  }
]

// 获取定时任务列表
const getList = () => {
  loading.value = true
  // 模拟 API 请求
  setTimeout(() => {
    jobList.value = mockJobs
    total.value = mockJobs.length
    loading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.jobId = undefined
  form.jobName = undefined
  form.jobGroup = undefined
  form.invokeTarget = undefined
  form.cronExpression = undefined
  form.misfirePolicy = '1'
  form.concurrent = '1'
  form.status = '0'
  form.remark = undefined
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.jobName = undefined
  queryParams.jobGroup = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.jobId)
  names.value = selection.map(item => item.jobName)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 任务状态修改
const handleStatusChange = (row) => {
  const text = row.status === '0' ? '启动' : '暂停'
  ElMessageBox.confirm(`确认要${text}${row.jobName}任务吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`${row.jobName}任务${text}成功`)
  }).catch(() => {
    row.status = row.status === '0' ? '1' : '0'
  })
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加定时任务'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  open.value = true
  title.value = '修改定时任务'
  form.jobId = row.jobId
  form.jobName = row.jobName
  form.jobGroup = row.jobGroup
  form.invokeTarget = row.invokeTarget
  form.cronExpression = row.cronExpression
  form.misfirePolicy = row.misfirePolicy
  form.concurrent = row.concurrent
  form.status = row.status
  form.remark = row.remark
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.jobId ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除定时任务编号为${row.jobId}的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`是否确认删除定时任务编号为${ids.value}的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  })
}

// 任务详情
const handleDetail = (row) => {
  detailVisible.value = true
  Object.assign(detailForm, row)
  nextExecuteTime.value = '2023-06-05 15:30:00' // 模拟下次执行时间
}

// 任务执行一次
const handleRun = (row) => {
  ElMessageBox.confirm(`确认要立即执行一次${row.jobName}任务吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`${row.jobName}任务执行成功`)
  })
}

// 批量执行一次
const handleBatchExecute = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要执行的任务')
    return
  }
  ElMessageBox.confirm(`确认要立即执行选中的${ids.value.length}个任务吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('执行成功')
  })
}

// 调度日志按钮操作
const handleJobLog = (row) => {
  const jobId = row?.jobId || ''
  ElMessage.info(`跳转到调度日志页面，任务ID: ${jobId}`)
  // 实际项目中应该是路由跳转
  // router.push({ path: '/monitor/job-log', query: { jobId: jobId } })
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 显示执行表达式弹窗
const handleShowCronForm = () => {
  cronVisible.value = true
}

// 显示调用测试弹窗
const handleShowInvokeTest = () => {
  ElMessage.success('调用成功')
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

onMounted(() => {
  // 获取定时任务列表
  getList()
})
</script>

<style scoped>
.job-container {
  padding: 20px;
}

.job-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.header-subtitle {
  font-size: 13px;
  color: #909399;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}
</style> 